<template>
  <el-dialog :visible="visible" width="80%" title="调研台账-季度导出" @close="$emit('close')">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="导出格式" prop="format">
            <jdf-common-input v-model="form.format" el-type="radio" :options="formatOptions" :is-edit="true">
              {{ form.format }}
            </jdf-common-input>
          </el-form-item>
          <el-form-item label="年份" prop="year">
            <el-select v-model="form.year" placeholder="请选择年份" size="small" @change="handleYearQuarterChange">
              <el-option v-for="year in years" :key="year" :label="year" :value="year" />
            </el-select>
          </el-form-item>
          <el-form-item label="季度" prop="quarter">
            <el-select v-model="form.quarter" placeholder="请选择季度" size="small" @change="handleYearQuarterChange">
              <el-option v-for="quarter in quarters" :key="quarter.value" :label="quarter.label" :value="quarter.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="导出项选择" prop="exportItems">
            <jdf-common-input v-model="form.exportItems" el-type="checkbox" :options="exportItemsOptions" :is-edit="true">
              {{ form.exportItems }}
            </jdf-common-input>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="16">
        <div class="table-container">
          <h3>数据预览:</h3>
          <jdf-table
            :columns="columns"
            :data="previewData"
            :table-attrs="{
              border: true,
              stripe: true,
            }"
          ></jdf-table>
        </div>
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button @click="$emit('close')">取消</el-button>
      <el-button type="primary" @click="handleSubmit">导出</el-button>
    </div>
  </el-dialog>
</template>

<script>
import dayjs from 'dayjs';
import { alertErrorMsg } from '@/api/utils/pc-message';
import { downloadFile } from 'jdf-util';
import ResearchLedgerService from '@/api/domains/ResearchLedgerService';
import { QUARTER_EXPORT_FORMAT_OPTIONS, QUARTER_YEAR_OPTIONS } from '@/utils/constants';

export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      service: new ResearchLedgerService(),
      form: {
        format: 'EXCEL',
        year: '',
        quarter: '',
        exportItems: [
          'index',
          'grassrootsContactName',
          'researchDate',
          'researchType',
          'leadingUserName',
          'researchSubject',
          'researchEntourageName',
          'resolvedProblemNumber',
          'conductResearchEntourageName',
          'detectProblemNumber',
          'researchUnitName',
        ],
      },
      rules: {
        format: [{ required: true, message: '请选择导出格式', trigger: 'blur' }],
        year: [{ required: true, message: '请选择年份', trigger: 'blur' }],
        quarter: [{ required: true, message: '请选择季度', trigger: 'blur' }],
        exportItems: [{ required: true, message: '请选择导出项', trigger: 'change' }],
      },
      years: [],
      // 导出格式
      formatOptions: QUARTER_EXPORT_FORMAT_OPTIONS,
      // 季度
      quarters: QUARTER_YEAR_OPTIONS,
      // 导出项
      exportItemsOptions: [
        { label: '序号', value: 'index', width: 50 },
        { label: '调研地点', value: 'grassrootsContactName', width: 100 },
        { label: '调研日期', value: 'researchDate', width: 150 },
        { label: '调研类型', value: 'researchType', width: 100 },
        { label: '带队领导', value: 'leadingUserName', width: 100 },
        { label: '调研主题', value: 'researchSubject', width: 100 },
        { label: '调研组成员', value: 'researchEntourageName', width: 100 },
        { label: '解决问题数', value: 'resolvedProblemNumber', width: 100 },
        { label: '被调研单位陪同人员', value: 'conductResearchEntourageName', width: 100 },
        { label: '带回解决问题数', value: 'detectProblemNumber', width: 100 },
        { label: '调研对象', value: 'researchUnitName', width: 100 },
      ],
      previewData: [],
    };
  },
  created() {
    const currentYear = dayjs().format('YYYY');
    this.years = [currentYear, currentYear - 1, currentYear - 2];
  },
  computed: {
    columns() {
      const optionsMap = {};
      this.exportItemsOptions.forEach((option) => {
        optionsMap[option.value] = option;
      });

      return this.form.exportItems.map((item) => {
        const { label, width, value } = optionsMap[item];
        return {
          label: label || item,
          prop: item,
          width: width,
          type: value
        };
      });
    },
  },
  methods: {
    handleYearQuarterChange() {
      if (this.form.year && this.form.quarter) {
        this.loadPreviewData();
      }
    },

    /**
     * 获取数据预览
     */
    async loadPreviewData() {
      try {
        const { service, form: { year, quarter: season } } = this;
        const data = await service.workArrangementSeasonData({ year, season });
        this.previewData = data || [];
      } catch (error) {
        alertErrorMsg(error);
      }
    },

    /**
     * 提交处理
     */
    handleSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            const { service, form: { format, year, quarter, exportItems } } = this;
            const params = {
              year,
              exportType: format,
              season: quarter,
              exportColumns: exportItems,
            };
            const blob = await service.exportSeasonData(params);
            downloadFile(blob);
          } catch (error) {
            alertErrorMsg(error);
          }
        }
      });
    },
  },
};
</script>

<style scoped>
.data-preview {
  margin-top: 20px;
}
</style>
